<template>
  <div class="app-container">
    <el-input v-model="search" placeholder="输入成品编号或名称搜索" size="mini" align="right"/>
    <el-table
      v-loading="Loading"
      :data="data.filter(data => !search || filterNoOrName(data,search))"
      :default-sort = "{prop: 'CreatedAt', order: 'descending'}"
      element-loading-text="Loading"
      style="width: 100%"
    >
      <el-table-column type="expand" class-name="column-background">
        <template slot-scope="props">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="客户电话">
              <span>{{ props.row.Tel }}</span>
            </el-form-item>
            <el-form-item label="客户地址">
              <span>{{ props.row.DeliveryAddress }}</span>
            </el-form-item>
            <el-form-item label="送货时间">
              <span>{{ props.row.DeliveryTime }}</span>
            </el-form-item>
            <el-form-item label="销售类型">
              <span>{{ props.row.OrderTrade }}</span>
            </el-form-item>
            <el-form-item label="销售渠道">
              <span>{{ props.row.OrderLine }}</span>
            </el-form-item>
            <el-form-item label="备注">
              <span>{{ props.row.Remarks }}</span>
            </el-form-item>
          </el-form>

          <el-table :data="props.row.Goods" style="width: 100%">
            <el-table-column label="编号" prop="No"/>
            <!--            <el-table-column label="类型" prop="Type"/>-->
            <el-table-column label="名称" prop="Name"/>
            <!--            <el-table-column label="成品库存" prop="StockNumber"/>-->
            <el-table-column label="单个成品进价(元)" prop="PurchasePrice"/>
            <el-table-column label="供应商" prop="Supply"/>
            <el-table-column label="库存" prop="StockNumber"/>
            <el-table-column label="数量" prop="Number"/>
            <el-table-column label="单位" prop="Unit"/>
          </el-table>
        </template>

      </el-table-column>
      <el-table-column
        :filters="[{ text: '未完成', value: '未完成' }, { text: '已完成', value: '已完成' }]"
        :filter-method="filterTag"
        label="状态"
        prop="State"/>
      <el-table-column label="客户" prop="Name"/>
      <el-table-column label="时间" prop="CreatedAt" sortable/>
      <el-table-column label="操作人" prop="Operator"/>
      <!--      <el-table-column label="订单总额" prop="Amount" sortable/>-->
      <!--      <el-table-column label="运费" prop="Freight" sortable/>-->

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.State === '未完成'" size="mini" type="primary" icon="el-icon-check" circle @click="handleConfirmOrder(scope.row)"/>
          <el-button v-if="scope.row.State === '未完成'" size="mini" type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"/>
          <el-button v-if="scope.row.State === '未完成'" size="mini" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)"/>
          <el-button size="mini" type="success" icon="el-icon-download" circle @click="handleDownload(scope.row)"/>
        </template>
      </el-table-column>
    </el-table>

    <!-- 更新表单 -->
    <el-dialog :visible.sync="dialogFormVisibleOrder" title="修改订单信息" width="99%">
      <el-form v-enterToNext="true" ref="postForm" :model="postForm" status-icon label-width="150px" >
        <el-form-item label="客户姓名" prop="Name">
          <el-select v-model="postForm.Name" filterable clearable placeholder="请选择" size="mini" @change="customerChange">
            <el-option
              v-for="item in customers"
              :key="item.ID"
              :label="item.Name"
              :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户电话" prop="Tel">
          <span>{{ postForm.Tel }}</span>
        </el-form-item>
        <el-form-item label="送货地址" prop="DeliveryAddress">
          <span>{{ postForm.DeliveryAddress }}</span>
        </el-form-item>
        <el-form-item label="销售类型" prop="OrderTrade">
          <el-select v-model="postForm.OrderTrade" filterable clearable placeholder="请选择" size="mini">
            <el-option
              v-for="item in orderTrades"
              :key="item.ID"
              :label="item.Name"
              :value="item.ID"/>
          </el-select>
        </el-form-item>
        <el-form-item label="销售渠道" prop="OrderLine">
          <el-select v-model="postForm.OrderLine" filterable clearable placeholder="请选择" size="mini">
            <el-option
              v-for="item in orderLines"
              :key="item.ID"
              :label="item.Name"
              :value="item.ID"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="Remarks">
          <el-input v-model="postForm.Remarks"/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisibleOrder = false">取 消</el-button>
        <el-button type="primary" @click="handleEditConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .column-background {
    background-color: gainsboro;
  }
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
</style>

<script>
import { getCustormerOrdersSub, deleteCustormerOrderSub, confirmCustormerOrderSub, updateSaleOrder } from '@/api/order'
import { parseTime } from '@/utils'
import { getCustomer } from '@/api/customer'

export default {
  data() {
    return {
      Loading: true,
      dialogFormVisibleOrder: false,
      data: [],
      customers: [],
      postForm: {
        ID: '',
        Name: '',
        Tel: '',
        DeliveryAddress: '',
        OrderTrade: '',
        OrderLine: '线下',
        Remarks: ''
      },
      search: '',
      orderTrades: [
        { ID: '内贸', Name: '内贸' },
        { ID: '外贸', Name: '外贸' }
      ],
      orderLines: [
        { ID: '线上', Name: '线上' },
        { ID: '线下', Name: '线下' }
      ]
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.Loading = true
      getCustormerOrdersSub().then(response => {
        console.log(response)
        const len = response.length
        for (let i = 0; i < len; i++) {
          response[i].CreatedAt = this.formatTime(response[i].CreatedAt)
        }
        this.data = response
        this.Loading = false
      })
      getCustomer().then(response => {
        console.log(response)
        this.customers = response.map(item => {
          return {
            ID: item.Name,
            Name: item.Name,
            Tel: item.Tel,
            Address: item.Address,
            EmailAddress: item.EmailAddress,
            Manager: item.Manager
          }
        })
      })
    },
    filterTag(value, row) {
      return row.State === value
    },
    handleConfirmOrder(data) {
      // this.$prompt('此操作将确认订单, 请输入运费:', '提示', {
      this.$confirm('此操作将确认此次销货！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
        // inputPattern: /^\d+(\.\d+)?$/,
        // inputErrorMessage: '请输入运费'
      })
        .then(() => {
          this.Loading = true
          confirmCustormerOrderSub(data.ID, { Freight: Number(0) })
            .then(response => {
              this.Loading = false
              this.$message.success('确认成功')
              this.fetchData()
            })
            .catch((error) => {
              this.Loading = false
              this.$message.error('确认失败: ' + error.response.data.error)
            })
        })
        .catch(() => {
          this.$message.info('已取消确认')
        })
    },
    handleDelete(data) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.Loading = true
          deleteCustormerOrderSub(data.ID)
            .then(response => {
              this.Loading = false
              this.$message.success('删除成功')
              this.fetchData()
            })
            .catch(() => {
              this.Loading = false
              this.$message.error('删除失败')
            })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    handleDownload(row) {
      this.Loading = true

       import('@/vendor/Export2Excel').then(excel => {
         const tHeader = ['客户姓名', '电话', '送货地点', '送货时间', '销售类型', '销售渠道', '编号', '名称', '单个成品进价(元)', '库存','供应商', '数量', '单位']
         const filterVal = ['CustomerName', 'Tel', 'DeliveryAddress', 'DeliveryTime', 'OrderTrade', 'OrderLine', 'No', 'Name', 'PurchasePrice', 'StockNumber' ,'Supply' ,'Number', 'Unit']
         const data = this.formatJson(filterVal, row.Goods)

         const len = filterVal.length
         const orderInfo = new Array(len)
         for (let i = 0; i < len; i++) {
           orderInfo[i] = undefined
         }
         orderInfo[0] = row.Name
         orderInfo[1] = row.Tel
         orderInfo[2] = row.DeliveryAddress
         orderInfo[3] = row.DeliveryTime
         orderInfo[4] = row.OrderTrade
         orderInfo[5] = row.OrderLine
         data.unshift(orderInfo)

         const fileName = '销货-' + row.Name + '-' + row.Tel + '-' + row.DeliveryAddress
         excel.export_json_to_excel({
           header: tHeader,
           data,
           autoWidth: true,
           filename: fileName
         })
       })
       this.Loading = false
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    formatTime(time) {
      return parseTime(time)
    },
    handleEdit(data) {
      this.dialogFormVisibleOrder = true
      this.postForm.ID = data.ID
    },
    handleEditConfirm() {
      this.Loading = true
      // this.postForm.Name = this.postForm.Name.Name
      updateSaleOrder(this.postForm.ID, this.postForm)
        .then(response => {
          console.log(response)
          this.$message.success('更新成功')
          this.Loading = false
          this.dialogFormVisibleOrder = false
          this.fetchData()
        })
        .catch(() => {
          this.Loading = false
          this.$message.error('更新失败')
        })
    },
    customerChange(item) {
      this.postForm.Name = item.Name
      this.postForm.Tel = item.Tel
      this.postForm.DeliveryAddress = item.EmailAddress
    },
    filterNoOrName(data, search) {
      var flag = false
      for (var i = 0; i < data.Goods.length ; i++) {
        if (String(data.Goods[i].Name).toLowerCase().includes(search.toLowerCase()) || String(data.Goods[i].No).toLowerCase().includes(search.toLowerCase())) { flag = true;break }
      }
      return flag
    }
  }
}
</script>
